<template>
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px;">
      <template #header>
        <div class="card-header">
          <img :src="imgURL" alt="">
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">{{ formType == 0 ? '注册账号' : '返回登录' }}</el-link>
      </div>
      <el-form ref="ruleFormRef" :model="loginForm" style="max-width: 600px" :rules="rules">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="loginForm.userName" placeholder="请输入账号">
            <template #prefix>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="passWord">
          <el-input v-model="loginForm.passWord" type="password" placeholder="请输入密码">
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="validCode" v-if="formType == 1">
          <el-input v-model="loginForm.validCode" placeholder="请输入验证码">
            <template #append><span @click="countdownChange">{{ countdown.validText }}</span></template>
            <template #prefix>
              <el-icon>
                <MessageBox />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <div style="width: 100%;display: flex;justify-content: space-evenly;align-items: center;">
          <el-button style="width: 50%;" type="primary" @click="submitForm(ruleFormRef)">{{ formType == 0 ? 'login' :
            'sign up!'
            }}</el-button>
          <el-button style="width: 50%;" @click="clearForm(ruleFormRef)">reset</el-button>
        </div>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { reactive, ref, computed, toRaw } from 'vue';
import { ElMessage } from 'element-plus';
import { getCode, userAuthentication, login, menuPermissions } from '../../api/index';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const store = useStore();

// 获取验证码

const router = useRouter();

const imgURL = new URL('../../assets/login/login-head.png', import.meta.url).href; // 登录页静态资源

/*
  @description: 登录页表单验证
  @author: Barry-Allen
  @date: 2024-09-24 14:30:00
  @elements : rules、submitForm、ruleFormRef(提交表单)
*/
const ruleFormRef = ref();
const rules = reactive({
  userName:
    [
      {
        required: true,
        message: '手机号不能为空!',
        trigger: 'blur'
      }
    ],
  passWord:
    [
      {
        required: true,
        min: 3,
        max: 20,
        message: '密码长度在3-20之间!',
        trigger: 'blur'
      },
    ],
  validCode: [
    {
      required: true,
      message: '验证码不能为空!',
      trigger: 'blur'
    }
  ]
})

const routerList = computed(() => store.state.menu.routerList);

// 表单验证函数
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (formType.value == 1) {
        userAuthentication(loginForm).then(res => {
          console.log(res);
          ElMessage({
            type: 'success',
            message: 'sign up ' + res.data.message + '!',
          }
          )
        })
        formType.value = 0;
      }
      else if (formType.value == 0) {
        login(loginForm).then(res => {
          ElMessage({
            type: 'success',
            message: 'login ' + res.data.message + '!',
          })
          // console.log(res.data);
          localStorage.setItem('pz_token', res.data.data.token);
          localStorage.setItem('pz_userInfo',JSON.stringify(res.data.data.userInfo));
          //获取用户权限
          menuPermissions().then(({data})=>{
            // console.log(data.data,'data');
            store.commit('dynamicMenu', data.data); //拼接menuPermissions接口提供的路由数据
            // console.log(store.state.menu.routerList,'routerList');
            toRaw(routerList.value).forEach(item => {
              // console.log(item);
              router.addRoute('main',item);
            });
            router.push('/');
          });
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
/*
  @description: 登录页表单类型-> 0:登录 1:注册
  @author: Barry-Allen
  @date: 2024-09-24 14:30:00
  @elements : formType、handleChange
*/
const formType = ref(0);//登录页表单类型-> 0:登录 1:注册

const handleChange = () => {// 点击切换登录和注册
  formType.value = formType.value == 0 ? 1 : 0;
}
/*
  @description:表单组件对象
  @author: Barry-Allen
  @date: 2024-09-24 14:30:00
  @elements : loginForm
*/
const loginForm = reactive({
  userName: '',
  passWord: '',
  validCode: ''
});

/*
  @description: 清空表单
  @author: Barry-Allen
  @date: 2024-09-24 14:30:00
  @elements : clearForm
*/

const clearForm = (formEl) => {// 清空表单
  loginForm.userName = '';
  loginForm.passWord = '';
  loginForm.validCode = '';

  if (!formEl) return
  formEl.resetFields()
}

/*
  @description: 发送验证码
*/
const countdown = reactive({
  validText: '获取验证码',
  time: 60,
  isClick: false
})

const countdownChange = () => {
  // 验证手机号
  const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    ElMessage({
      message: '请确认手机号是否正确!',
      type: 'warning'
    })
    return;
  }
  //发送验证码
  getCode({ tel: loginForm.userName }).then((data) => {
    // console.log(data,'data');
    ElMessage({
      message: data.data.msg,
      type: 'success',
    })
  }
  )
  //处理重复点击
  if (countdown.isClick) {
    ElMessage({
      message: '请勿重复点击!',
      type: 'warning',
    })
    return;
  } else {
    countdown.isClick = true;
  }
  // 验证码倒计时
  let timmer = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.time = 60;
      countdown.validText = '获取验证码';
      countdown.isClick = false;
      clearInterval(timmer);
    } else {
      countdown.time--;
      countdown.validText = countdown.time + 's后重新发送';
    }

  }, 1000);
}
</script>

<style scoped lang="less">
:deep(.el-card__header) {
  padding: 0
}

.login-container {
  height: 100%;

  .card-header {
    background-color: #899fe1;

    img {
      width: 430px;
    }
  }

  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>